(function () {

    Array.prototype.remove = function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) {
                this.splice(i, 1);
                break;
            }
        }
    };
    var DataSourceParamStore = {};
    window.DataSource = function (config) {
        if (typeof(config) == 'string') {
            config = {url: config, try: null, transform: null};
        }
        var base = "";
        if (config.url) {
            base = config.url.substring(0, config.url.lastIndexOf('/') + 1);
        }

        function fixurl(url) {
            if (url.indexOf('/') == 0) {
                return url;
            }
            return base + url;
        }

        var params = {
            step: 20,
            page: 1
        };
        params = _.extend(params, config.params);
        if (config.name) {
            var oldParams = DataSourceParamStore[config.name];
            if (oldParams) {
                params = oldParams;
            } else {
                DataSourceParamStore[config.name] = params;
            }
        }
        return {
            data: [],
            page_sizes: [20, 40, 100],
            pk: 'id',
            loading: false,
            total: config.total ? config.total : 0,
            params: params,
            selection: [],

            load: function (page) {
                if (page) {
                    this.params.page = page;
                }
                var me = this;
                this.loading = true;
                if (config.data) {
                    console.log('数据模拟请求' + config.url);
                    console.log('参数' + JSON.stringify(this.params));
                    setTimeout(function () {
                        me.loading = false;
                        var data = config.data();
                        me.data.length = 0;
                        data.forEach(function (element) {
                            me.data.push(element);
                        });
                    }, 300);
                } else {
                    me.data.length = 0;
                    axios.get(config.url, {
                        responseType: 'json',
                        params: me.params,
                        transformResponse: function (data) {
                            if (config.transform) {
                                data = config.transform(data);
                            }
                            return data;
                        }
                    }).then(function (response) {
                        me.loading = false;
                        var result = response.data;
                        var data = result;
                        if (!(result instanceof Array)) {
                            data = result.data;
                            me.total = result.total;
                        }
                        me.data.length = 0;
                        _.each(data, function (item) {
                            me.data.push(item);
                        });

                    })
                        .catch(function (error) {
                            me.loading = false;
                            console.log(error);
                        });
                }
            }, sizeChange: function (step) {
                this.params.step = step;
                this.load();
            }, select: function (val) {
                this.selection = val;
            }, do: function (action, url, row, params,load) {
                url = fixurl(url);
                var me = this;
                var p = Rap.promise().resolve();
                if (action) {
                    p = App.$confirm(action, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    });
                }
                p.then(function () {
                    me.loading = true;
                    axios.post(url, params).then(function () {
                        me.loading = false;
                        if (!load&&row) {
                            _.extend(row, params);
                        } else {
                            me.load(1);
                        }
                        App.$message({
                            type: 'success',
                            message: '操作成功!'
                        });
                    });
                }).catch(function () {

                });
            }, input: function (action, url, name, params, def) {
                url = fixurl(url);
                var me = this;
                App.$prompt(action, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValue: def
                }).then(function (what) {
                    if (what.value) {
                        if (!params) {
                            params = {};
                        }
                        params[name] = what.value;
                        axios.post(url, params).then(function () {
                            me.load(1);
                            App.$message({
                                type: 'success',
                                message: '修改成功!'
                            });
                        });
                    }
                }).catch(function () {
                });
            }
            , allDo: function (action, url, params) {
                url = fixurl(url);
                var me = this;
                var selection = this.selection;
                if (selection.length == 0) {
                    App.$message('请先选择');
                    return;
                }
                var ids = _.pluck(selection, this.pk);
                if (!params) {
                    params = {}
                }
                params.ids = ids;
                App.$confirm('你确定' + action + '选中的' + selection.length + "项吗", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    axios.post(url, params).then(function () {
                        me.load(1);
                        App.$message({
                            type: 'success',
                            message: action + '成功!'
                        });
                    });
                }).catch(function () {

                });
            }, search: function (key ) {
                var me=this;
                return function (query) {
                    me.params[key]=query;
                    me.load(1);
                };
            }, sort: function (sort) {
                if (!sort.order) {
                    this.params.sort = '';
                } else if (sort.order == 'ascending') {
                    this.params.sort = sort.prop + ' asc';
                } else {
                    this.params.sort = sort.prop + ' desc';
                }
                this.load(1);

            },
            //更新表中任意字段(column)的值为value
            updateColumn: function (id, column, value, action, url) {
                var me = this;
                App.$confirm('您确认' + action + '该项吗？', '操作提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    axios.post(url, {id: id, column: column, value: value}).then(function (rs) {
                        if (rs.data.success) {
                            me.load();
                            App.$message({
                                type: 'success',
                                message: '操作成功!'
                            });
                        } else {
                            App.$message({
                                type: 'error',
                                message: rs.msg
                            });
                        }

                    });
                }).catch(function () {

                });
            }
        }
    };

    Vue.component('editor', {
        props: {
            value: ""
        },
        template: "<textarea v-model='content'></textarea>",
        data: function () {
            return {
                content: ''
            }
        },
        watch: {
            'value': function () {
                if (this.ueditor && this.ueditor.isReady) {
                    var html = this.ueditor.getContent();
                    if (html != this.value) {
                        this.ueditor.setContent(this.value + "");
                    }
                }
            }
        },
        mounted: function () {
            var ue = this.ueditor = new UE.ui.Editor();
            var height = this.$el.parentNode.clientHeight - 80;
            ue.render(this.$el);
            window.ue = ue;

            var me = this;
            ue.ready(function () {

                ue.setHeight(height);
                if (me.value) {
                    me.ueditor.setContent(me.value + "");
                }
                ue.addListener('contentChange', function (content) {

                    var html = ue.getContent();
                    me.$emit('update:value', html);
                });
            });

        }
    });

    Vue.component('chart', VueECharts);

    Vue.filter('price', function (value) {
        return '¥' + (value / 100).toFixed(2);
    });


    axios.interceptors.request.use(function (config) {
        if (config.loading) {
            config.loading = App.$loading();
        }
        return config;
    }, function (error) {
        return Promise.reject(error);
    });

    axios.interceptors.response.use(function (response, config) {
        var loading = response.config.loading;
        if (loading) {
            loading.close();
        }
        var data = response.data;
        if (!data.success) {
            if (data.code == '100000') {
                // data.code
                var msg = data.msg;
                App.$message({
                    type: 'error',
                    message: msg
                });
                //抛出异常防止继续
                throw data;
            } else if (data.code == '1001') {
                App.$confirm('用户登录状态状态丢失,重新登录', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function (what) {
                    location.reload();
                }).catch(function () {
                    location.reload();
                });
                throw data;
            }

        }
        return response;
    }, function (error) {
        return Promise.reject(error);
    });
    var windowSize = {};

    function resize() {
        document.getElementById(app);
        app.style.height = window.innerHeight + "px";
        windowSize.width = window.innerWidth;
        windowSize.height = window.innerHeight;
    }

    window.addEventListener('resize', resize);
    resize();

    {
        var configs = {};
        //
        //
        // var xhr;
        // if (window.XMLHttpRequest) {
        //     xhr = new XMLHttpRequest();//W3C
        // } else {
        //     xhr = new ActiveXObject('MicroSoft.XMLHTTP');//IE
        // }
        // xhr.open('get', '/admin/configs', false);
        // xhr.send(null);
        // if (xhr.status == 200) {
        //     content=xhr.responseText;
        //     configs=JSON.parse(content);
        //     document.title= configs.global.shop.name;
        // }
        Vue.mixin({
            data: function () {
                return {
                    app: {
                        configs: configs,
                        size: windowSize,
                        configInput: function (action, module, key) {
                            var value = configs[module][key];
                            var url = '/admin/config';
                            App.$prompt(action, '提示', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                inputValue: value
                            }).then(function (what) {
                                if (what.value) {
                                    var data = {};
                                    data[key] = what.value;
                                    axios.post(url, {
                                        module: module,
                                        data: data
                                    }).then(function () {
                                        App.$message({
                                            type: 'success',
                                            message: '修改成功!'
                                        });
                                        configs[module][key] = what.value;
                                    });
                                }
                            }).catch(function () {
                            });
                        }
                    }
                };
            }
        });

        //将对象转成url 参数
        window.Service = {
            config: function (module, key) {
                var result = configs[module];
                if (key) {
                    result = result[key];
                }
                if (!result) {
                    return null;
                }
                return JSON.parse(JSON.stringify(result));
            },
            editConfig: function (module, data, call) {
                var url = '/admin/config';
                axios.post(url, {
                    module: module,
                    data: data
                }).then(function () {
                    App.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    _.extend(configs[module], data);
                    if (call) {
                        call();
                    }
                });
            },
            //设置cookie
            setCookie: function (cname, cvalue, exdays) {
                var d = new Date();
                d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
                var expires = "expires=" + d.toUTCString();
                console.info(cname + "=" + cvalue + "; " + expires);
                document.cookie = cname + "=" + cvalue + "; " + expires;
                console.info(document.cookie);
            },
            //获取cookie
            getCookie: function (cname) {
                var name = cname + "=";
                var ca = document.cookie.split(';');
                console.log("获取cookie,现在循环")
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    console.log(c)
                    while (c.charAt(0) == ' ') c = c.substring(1);
                    if (c.indexOf(name) != -1) {
                        return c.substring(name.length, c.length);
                    }
                }
                return "";
            },
            //删除cookie
            delCookie: function (name) {
                var exp = new Date();
                exp.setTime(exp.getTime() - 1);
                var cval = this.getCookie(name);
                if (cval != null)
                    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
            }
        };
    }

})();